﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data;
using Workflow.Interface;
using MyLib;
using System.Text;
using Portal.Logic;
using System.Collections;
using System.ComponentModel;
using Portal.Interface;
using Portal.Entity;
using ProcessControl.Entity;
using ProcessControl.Logic;

namespace ProcessControl
{
    public partial class ButtonList : System.Web.UI.UserControl
    {
        public event CancelEventHandler BeforeSubmit;
        public event CancelEventHandler AfterSubmit;
        ITask _task = ServiceContainer.Instance().GetService<ITask>();
        protected void Page_Load(object sender, EventArgs e)
        {
            UserInfo userInfo = Page.FindControl("UserInfo1") as UserInfo;
            if (userInfo.Incident == "0" || userInfo.Incident == "")
            {
            }
            else
            {
                btnSaveDraft.Visible = false;
            }
            if (string.IsNullOrEmpty(userInfo.TaskId))
            {
                btnSubmit.Visible = false;
            }
            if (Request.QueryString["Type"].ToUpper().Trim() == "DRAFT")
            {
                btnSaveDraft.Visible = true;
                btnSubmit.Visible = true;
            }


            string type = Request.QueryString["Type"];
            if (!string.IsNullOrEmpty(type))
            {
                if (type.ToUpper() == "MYAPPROVAL" || type.ToUpper() == "MYREQUEST") //已完成，不显示提交按钮
                {
                    btnSubmit.Visible = false;
                }
            }
            // 已完成任务禁用
            string taskid = Request.QueryString["TaskID"];//TaskID
            if (!string.IsNullOrEmpty(taskid) && !taskid.StartsWith("S"))
            {
                CommonLogic cl = new CommonLogic();
                int iStatus = cl.GetTaskStatusBySql(taskid);
                if (iStatus != 1)
                {
                    btnSubmit.Visible = false;
                }
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string strApplicantAccout = null;
            try 
            {
                UserInfo userInfo = Page.FindControl("UserInfo1") as UserInfo;
                if (string.IsNullOrEmpty(Page.User.Identity.Name) || string.IsNullOrEmpty(((TextBox)userInfo.FindControl("var_ApplicantAccount")).Text.Replace("/", "\\"))) //没有登录或者用户取不到 
                {
                    LogUtil.Info("B001提交失败！未找到用户信息 IdentityName:" + Page.User.Identity.Name + " SessionUserName:" + ConvertUtil.ToString(HttpContext.Current.Session["userAccount"]));
                    strApplicantAccout = ((TextBox)userInfo.FindControl("txtApplicantAccount")).Text.Replace("/", "\\");
                    if (strApplicantAccout.Trim() == "")
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('提交失败！未找到用户信息！');", true);
                        return;
                    }

                }
                else
                {
                    strApplicantAccout = Page.User.Identity.Name;
                }
                LogUtil.Info("B002提交！IdentityName:" + strApplicantAccout + " SessionUserName:" + ConvertUtil.ToString(HttpContext.Current.Session["userAccount"]));

                if (BeforeSubmit != null) //开始执行之前的自定义事件GetFormDataGetFormData
                {
                    CancelEventArgs cea = new CancelEventArgs();
                    BeforeSubmit(sender, cea);
                    if (cea.Cancel)
                    {
                        return;
                    }
                }


                //(userInfo.FindControl("var_FinanceUser"))
                //----------------------添加财务人员---------modify by Sky  2013-6-13 18:37
                string strProcess = ((TextBox)userInfo.FindControl("fld_PROCESSNAME")).Text.Trim();
                string strCompany = ((DropDownList)userInfo.FindControl("fld_COMPANY")).SelectedItem.Text.Trim();
                string strCenterDept = ((TextBox)userInfo.FindControl("var_CenterDepartment")).Text.Trim();
                string strSubDeptid = ((TextBox)userInfo.FindControl("var_DepartmentId")).Text.Trim();
                string strCasier = "";
                string strFinancer = "";
                ApprovalHistoryLogic al = new ApprovalHistoryLogic();
                al.GetFinancePerson(strProcess, strCompany, strCenterDept, strSubDeptid, ref strFinancer, ref strCasier);
                ((TextBox)userInfo.FindControl("var_FinanceUser")).Text = strFinancer;
                ((TextBox)userInfo.FindControl("var_Cashier")).Text = strCasier;
                //-------------------------------------------------------------------------
                ApprovalHistory approvalHistory = Page.FindControl("ApprovalHistory1") as ApprovalHistory;
                DataSet ds = userInfo.GetFormData();
                string tableName = userInfo.TableName;
                string tableDetail = userInfo.TableNameDetail;
                string tag = "@";

                //获取流程编号
                string documentNo = "";
                //SerialNoLogic sn = new SerialNoLogic();
                //string documentNo = string.Format("{0}{1}{2}{3}{4}", userInfo.ProcessPrefix, DateTime.Now.Year, DateTime.Now.Month.ToString().PadLeft(2, '0'), DateTime.Now.Day.ToString().PadLeft(2, '0'), sn.GetSerialNo(userInfo.ProcessPrefix, DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).ToString().PadLeft(3, '0'));
                //创建事务
                IDbTransaction trans = null;
                //trans = DataAccess.Instance("BizDB").BeginTransaction();

                IDbCommand cmd = DataAccess.Instance("BizDB").GetDbCommand();
                if (ConfigurationManager.ConnectionStrings["BizDB"].ProviderName.ToUpper().IndexOf("ORACLE") >= 0)
                {
                    tag = ":";
                }
                //1.保存主表数据
                StringBuilder sb = new StringBuilder();
                string processName = userInfo.ProcessName;
                string incident = userInfo.Incident;
                string formId = userInfo.FormId;
                int inc = ConvertUtil.ToInt32(incident);

                int oldInc = inc > 1000000 ? 0 : inc;
                inc = oldInc;
                Hashtable vars = new Hashtable();
                foreach (DataTable dt in ds.Tables)
                {

                    if (dt.Rows.Count == 0)
                    {
                        continue;
                    }
                    if (dt.TableName == tableDetail && dt != null)
                    {
                        //1.0 明细表插入
                        sb.AppendFormat("DELETE FROM {0} WHERE  FORMID='{1}';", tableDetail, formId);
                        foreach (DataRow row in dt.Rows)
                        {
                            StringBuilder sbItem = new StringBuilder();
                            StringBuilder sbItemValue = new StringBuilder();
                            foreach (DataColumn col in dt.Columns)
                            {
                                sbItem.Append(col.ColumnName + ",");
                                sbItemValue.Append("'" + row[col.ColumnName].ToString().Replace("'", "''") + "',");
                            }
                            sb.AppendFormat("insert into {0}({1}) values({2});", tableDetail, sbItem.ToString().TrimEnd(','), sbItemValue.ToString().TrimEnd(','));
                        }
                    }
                    if (dt.TableName == "MainTable")
                    {
                        string strQuery = "select count(1) from " + tableName + " where formid ='" + formId + "'";
                        int iCount = ConvertUtil.ToInt32(DataAccess.Instance("BizDB").ExecuteScalar(strQuery));
                        //1.1 判断是新建申请还是待办任务
                        if (iCount > 0)
                        {
                            StringBuilder sbItem = new StringBuilder();
                            //1.1.1 存在更新
                            foreach (DataColumn col in dt.Columns)
                            {
                                sbItem.AppendFormat("{0}={1}{0},", col.ColumnName, tag);
                                IDbDataParameter para = cmd.CreateParameter();
                                para.ParameterName = col.ColumnName;
                                para.Value = dt.Rows[0][col.ColumnName].ToString();
                                if (col.ColumnName.ToUpper().IndexOf("DATE") >= 0 && para.Value.ToString() != "")
                                {
                                    para.DbType = DbType.Date;
                                }
                                cmd.Parameters.Add(para);
                                LogUtil.Info("变量" + col.ColumnName + "值：" + dt.Rows[0][col.ColumnName].ToString());
                                vars.Add(col.ColumnName, dt.Rows[0][col.ColumnName].ToString());
                            }
                            sb.AppendFormat("update {0} set {1} where FORMID='{2}';", tableName, sbItem.ToString().TrimEnd(','), formId);

                        }
                        else
                        {
                            //1.1.2 不存在，插入
                            StringBuilder sbItem = new StringBuilder();
                            StringBuilder sbItemValue = new StringBuilder();
                            foreach (DataColumn col in dt.Columns)
                            {
                                sbItem.AppendFormat("{0},", col.ColumnName);
                                sbItemValue.AppendFormat("{1}{0},", col.ColumnName, tag);
                                IDbDataParameter para = cmd.CreateParameter();
                                para.ParameterName = col.ColumnName;
                                para.Value = dt.Rows[0][col.ColumnName].ToString();
                                if (col.ColumnName.ToUpper().IndexOf("DATE") >= 0 && para.Value.ToString() != "")
                                {
                                    para.DbType = DbType.Date;
                                }
                                cmd.Parameters.Add(para);
                                vars.Add(col.ColumnName, dt.Rows[0][col.ColumnName].ToString());
                            }
                            sb.AppendFormat("insert into {0}({1}) values({2});", tableName, sbItem.ToString().TrimEnd(','), sbItemValue.ToString().TrimEnd(','));
                        }
                    }
                }

                try
                {
                    if (sb.Length > 0) //1.2 写入业务库
                    {
                        //cmd.Transaction = trans;
                        LogUtil.Info(sb.ToString());
                        if (cmd.Connection.State == ConnectionState.Closed)
                        {
                            cmd.Connection.Open();
                        }
                        cmd.CommandText = "begin " + sb.ToString() + " end;";
                        cmd.ExecuteNonQuery();
                        //if (sb.Length > 0)
                        //{
                        //    trans.Commit();
                        //}
                    }
                    else
                    {
                        LogUtil.Info("B003提交失败！未获取表单信息!");
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('提交失败！未获取表单信息!');", true);
                        return;
                    }
                    //2.提交

                    
                    string error = "";
                    if (inc == 0 || userInfo.Type.ToUpper().Trim() == "DRAFT" || userInfo.StepName == "重新发起" || userInfo.StepName == "重发起") //判断是新建申请还是待办任务，只在新建申请时才保存单独的电子表格变量（另外步骤的通过设置fld_的方式保存电子表格变量）
                    {
                        userInfo.GetFormVars(ref vars);
                    }
                    
                    string userName = strApplicantAccout;
                    //ConvertUtil.ToInt32
                    if (ConvertUtil.ToInt32(approvalHistory.ActionType, 0) == 0) //新建或者同意
                    {
                        if (inc == 0)//发起申请:这里把申请人替换为部门公用账号，规则为"Ultimus/D"+部门ID
                        {
                            IOrg org = ServiceContainer.Instance().GetService<IOrg>();
                            UserEntity user = org.GetUserEntity(strApplicantAccout);
                            userName = ConfigurationManager.AppSettings["DomainName"] + "/D" + ConvertUtil.ToInt32(user.Ext02).ToString();
                        }
                        LogUtil.Info("SubmitTask(" + userName + "," + userInfo.TaskId + "," + userInfo.Summary + "," + vars.Count.ToString() + ", true, ref " + inc + ")");
                        error = _task.SubmitTask(userName, userInfo.TaskId, userInfo.Summary, vars, true, ref inc);
                    }
                    if (ConvertUtil.ToInt32(approvalHistory.ActionType, 0) == 1) //退回
                    {
                        //退回的时候 删除会签任务。     modify by Sky 2013-6-7 18:00
                        string strSql = string.Format("delete from tasks t where t.taskid!='{0}' and t.steplabel='{1}' and t.processname='{2}' and t.incident={3} ", userInfo.TaskId, userInfo.StepName, userInfo.ProcessName, userInfo.Incident);
                        DataAccess.Instance("UltDB").ExecuteNonQuery(strSql);
                        //---------------------------------------------------------
                        error = _task.ReturnTask(strApplicantAccout, userInfo.TaskId, "", userInfo.Summary, vars, true);
                    }
                    if (!string.IsNullOrEmpty(error) || inc == 0) //2.1提交失败
                    {
                        //if (sb.Length > 0)
                        //{
                        // trans.Rollback();
                        //}
                        //DataAccess.Instance("BizDB").ExecuteNonQuery(string.Format("update {0} set INCIDENT={1},  STATUS=0 where FORMID='{2}'", tableName, Convert.ToInt32(DateTime.Now.ToOADate() * 10000), formId));
                        //}
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('提交失败，错误信息：" + error , true);
                        return;
                    }
                    else //2.2提交成功
                    {
                        if (oldInc == 0 || userInfo.Type.ToUpper().Trim() == "DRAFT") //新建申请时
                        {
                            //2.2.1 更新实例号和流程编号
                            DataAccess.Instance("BizDB").ExecuteNonQuery(string.Format("update {0} set INCIDENT={1},  STATUS=1 where FORMID='{2}'", tableName, inc, formId));
                            LogUtil.Info("实例号"+inc.ToString());
                            //2.2.2 插入真正的发起人
                            LogUtil.Info("UserAccount:" + strApplicantAccout);

                            LogUtil.Info(string.Format("insert into WF_APPLICANT(PROCESSNAME,INCIDENT,APPLICANT,DEPARTMENTACCOUNT) VALUES('{0}',{1},'{2}','{3}')",
                                userInfo.ProcessName, inc, strApplicantAccout.Replace("\\", "/"), userName));

                            DataAccess.Instance("BizDB").ExecuteNonQuery(
                                string.Format("insert into WF_APPLICANT(PROCESSNAME,INCIDENT,APPLICANT,DEPARTMENTACCOUNT) VALUES('{0}',{1},'{2}','{3}')",
                                userInfo.ProcessName, inc, strApplicantAccout.Replace("\\", "/"), userName));

                            //2.2.3 删除草稿箱
                            DataAccess.Instance("BizDB").ExecuteNonQuery(string.Format("DELETE FROM WF_DRAFT WHERE FORMID='{0}'", formId));
                        }
                        //插入审批历史记录
                        ApprovalHistoryEntity approval = new ApprovalHistoryEntity();
                        if (approvalHistory.ActionType == 0 && oldInc == 0)
                        {
                            approval.Action = "发起申请";
                        }
                        if (approvalHistory.ActionType == 0 && oldInc > 0)
                        {
                            approval.Action = "同意";
                        }
                        if (approvalHistory.ActionType == 1)
                        {
                            approval.Action = "退回";
                        }
                        approval.ApproveDate = DateTime.Now;
                        IOrg _org = ServiceContainer.Instance().GetService<IOrg>();
                        UserEntity user = _org.GetUserEntity(strApplicantAccout);

                        if (string.IsNullOrEmpty(user.CNName.Trim()))
                        {
                            if (string.IsNullOrEmpty(strApplicantAccout))
                            {
                                LogUtil.Info(userInfo.ProcessName + ConvertUtil.ToInt32(inc) + userInfo.StepName + "：审批人为空！");
                                Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('提交失败！审批人为空！');", true);
                                return;
                            }
                            else
                            {
                                string str = "select * from zhr_employee_oa a where a.pernr=" + strApplicantAccout.Replace("\\", "/").Split('/')[1].ToString();
                                DataTable dtApprover = DataAccess.Instance("BizDB").ExecuteDataTable(str);
                                user.CNName = dtApprover.Rows[0]["ename"].ToString();
                            }
                        }

                        approval.Approver = user.CNName;
                        approval.Comments = approvalHistory.Comments;
                        approval.Ext01 = strApplicantAccout;
                        approval.ProcessName = userInfo.ProcessName;
                        approval.Incident = ConvertUtil.ToInt32(inc);
                        approval.StepName = userInfo.StepName == "" ? "填写申请" : userInfo.StepName;
                        ApprovalHistoryLogic ahl = new ApprovalHistoryLogic();
                        ahl.AddApprovalHistory(null, approval);

                        if (AfterSubmit != null) //自定义扩展事件
                        {
                            CancelEventArgs ce = new CancelEventArgs();
                            AfterSubmit(trans, ce);
                            if (ce.Cancel)
                            {
                                //  trans.Rollback();
                                return;
                            }

                        }
                        //if (sb.Length > 0)
                        //{
                        //    trans.Commit();
                        //}
                    }

                }
                catch
                {
                    if (sb.Length > 0)
                    {

                        // trans.Rollback();
                    }
                    throw;
                }
                finally
                {
                    //if (trans.Connection != null)
                    //{
                    //    if (trans.Connection.State == ConnectionState.Open)
                    //    {
                    //        trans.Connection.Close();
                    //        trans.Connection.Dispose();
                    //    }
                    //}
                    if (cmd.Connection.State == ConnectionState.Open)
                    {
                        cmd.Connection.Close();
                        cmd.Connection.Dispose();
                        cmd.Dispose();
                    }
                    if (trans != null)
                    {
                        trans.Dispose();
                    }
                }
            }
            catch (Exception ex) //意外终止
            {
                LogUtil.Info("提交失败!");
                Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('提交失败!错误信息：" + ex.Message.Replace("'", "").Replace("\r", "").Replace("\n", "") + "');", true);
            }

            Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "submitSuccess();", true);
        }


        protected void btnSaveDraft_Click(object sender, EventArgs e)
        {
            try
            {
                string strApplicantAccount = "";
                UserInfo userInfo = Page.FindControl("UserInfo1") as UserInfo;
                if (string.IsNullOrEmpty(Page.User.Identity.Name)) //没有登录或者用户取不到 
                {
                    LogUtil.Info("B005提交失败！未找到用户信息 IdentityName:" + Page.User.Identity.Name + " SessionUserName:" + ConvertUtil.ToString(HttpContext.Current.Session["userAccount"]));
                    strApplicantAccount = ((TextBox)userInfo.FindControl("txtApplicantAccount")).Text.Replace("/", "\\");
                    if (strApplicantAccount.Trim() == "")
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('提交失败！未找到用户信息！');", true);
                        return;
                    }
                }
                else
                {
                    strApplicantAccount = Page.User.Identity.Name;
                }
                LogUtil.Info("B006提交！IdentityName:" + strApplicantAccount + " SessionUserName:" + ConvertUtil.ToString(HttpContext.Current.Session["userAccount"]));


                ApprovalHistory approvalHistory = Page.FindControl("ApprovalHistory1") as ApprovalHistory;
                DataSet ds = userInfo.GetFormData();
                string tableName = userInfo.TableName;
                string tableDetail = userInfo.TableNameDetail;
                string tag = "@";

                //获取流程编号
                string documentNo = "";
                //SerialNoLogic sn = new SerialNoLogic();
                //string documentNo = string.Format("{0}{1}{2}{3}{4}", userInfo.ProcessPrefix, DateTime.Now.Year, DateTime.Now.Month.ToString().PadLeft(2, '0'), DateTime.Now.Day.ToString().PadLeft(2, '0'), sn.GetSerialNo(userInfo.ProcessPrefix, DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).ToString().PadLeft(3, '0'));
                //创建事务
                IDbTransaction trans = null;
                //trans = DataAccess.Instance("BizDB").BeginTransaction();
                IDbCommand cmd = DataAccess.Instance("BizDB").GetDbCommand();
                if (ConfigurationManager.ConnectionStrings["BizDB"].ProviderName.ToUpper().IndexOf("ORACLE") >= 0)
                {
                    tag = ":";
                }
                //1.保存主表数据
                StringBuilder sb = new StringBuilder();
                string processName = userInfo.ProcessName;
                string incident = userInfo.Incident;
                string formId = userInfo.FormId;
                int inc = ConvertUtil.ToInt32(incident);
                int oldInc = inc;
                Hashtable vars = new Hashtable();
                foreach (DataTable dt in ds.Tables)
                {

                    if (dt.Rows.Count == 0)
                    {
                        continue;
                    }
                    if (dt.TableName == tableDetail && dt != null)
                    {
                        //1.0 明细表插入
                        sb.AppendFormat("DELETE FROM {0} WHERE  FORMID='{1}';", tableDetail, formId);
                        foreach (DataRow row in dt.Rows)
                        {
                            StringBuilder sbItem = new StringBuilder();
                            StringBuilder sbItemValue = new StringBuilder();
                            foreach (DataColumn col in dt.Columns)
                            {
                                sbItem.Append(col.ColumnName + ",");
                                sbItemValue.Append("'" + row[col.ColumnName].ToString().Replace("'", "''") + "',");
                            }
                            sb.AppendFormat("insert into {0}({1}) values({2});", tableDetail, sbItem.ToString().TrimEnd(','), sbItemValue.ToString().TrimEnd(','));
                        }
                    }
                    if (dt.TableName == "MainTable")
                    {

                        //1.1 判断是新建申请还是待办任务
                        //if (inc > 0)
                        //{
                        //StringBuilder sbItem = new StringBuilder();
                        ////1.1.1 存在更新
                        //foreach (DataColumn col in dt.Columns)
                        //{
                        //    sbItem.AppendFormat("{0}={1}{0},", col.ColumnName, tag);
                        //    IDbDataParameter para = cmd.CreateParameter();
                        //    para.ParameterName = col.ColumnName;
                        //    para.Value = dt.Rows[0][col.ColumnName].ToString();
                        //    if (col.ColumnName.ToUpper().IndexOf("DATE") >= 0 && para.Value.ToString() != "")
                        //    {
                        //        para.DbType = DbType.Date;
                        //    }
                        //    cmd.Parameters.Add(para);
                        //    vars.Add(col.ColumnName, dt.Rows[0][col.ColumnName].ToString());
                        //}
                        sb.AppendFormat("delete from {0} where FORMID='{1}';", tableName, formId);

                        //}
                        //else
                        //{
                        //1.1.2 不存在，插入
                        StringBuilder sbItem = new StringBuilder();
                        StringBuilder sbItemValue = new StringBuilder();
                        foreach (DataColumn col in dt.Columns)
                        {
                            sbItem.AppendFormat("{0},", col.ColumnName);
                            sbItemValue.AppendFormat("{1}{0},", col.ColumnName, tag);
                            IDbDataParameter para = cmd.CreateParameter();
                            para.ParameterName = col.ColumnName;
                            para.Value = dt.Rows[0][col.ColumnName].ToString();
                            if (col.ColumnName.ToUpper().IndexOf("DATE") >= 0 && para.Value.ToString() != "")
                            {
                                para.DbType = DbType.Date;
                            }
                            cmd.Parameters.Add(para);
                            LogUtil.Info("草稿箱变量" + col.ColumnName + "值：" + dt.Rows[0][col.ColumnName].ToString());
                            vars.Add(col.ColumnName, dt.Rows[0][col.ColumnName].ToString());
                        }
                        sb.AppendFormat("insert into {0}({1}) values({2});", tableName, sbItem.ToString().TrimEnd(','), sbItemValue.ToString().TrimEnd(','));
                        //}
                    }
                }

                try
                {
                    if (sb.Length > 0) //写入业务库
                    {
                        // cmd.Transaction = trans;
                        if (cmd.Connection.State == ConnectionState.Closed)
                        {
                            cmd.Connection.Open();
                        }
                        cmd.CommandText = "begin " + sb.ToString() + " end;";
                        cmd.ExecuteNonQuery();
                    }
                    else
                    {
                        LogUtil.Info("B007提交失败！未获取表单信息!");
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('提交失败！未获取表单信息!');", true);
                        return;
                    }

                    if (sb.Length > 0)
                    {
                        inc = ConvertUtil.ToInt32(DateTime.Now.ToOADate() * 10000);
                        DataAccess.Instance("BizDB").ExecuteNonQuery(string.Format("update {0} set STATUS=0,incident={2} where FORMID='{1}'", tableName, formId, inc));
                        DataAccess.Instance("BizDB").ExecuteNonQuery(string.Format("DELETE FROM WF_DRAFT WHERE FORMID='{0}'", formId));
                        DataAccess.Instance("BizDB").ExecuteNonQuery(string.Format("insert into WF_DRAFT(PROCESSNAME,FORMID,TABLENAME,SUMMARY,CREATEDATE,CREATEBY,INCIDENT,STEPNAME,TASKID) VALUES('{0}','{1}','{2}','{3}','{4}','{5}',{6},'{7}','{8}')", processName, formId, userInfo.TableName + "," + userInfo.TableNameDetail, userInfo.Summary, DateTime.Now, strApplicantAccount, inc, userInfo.StepName, userInfo.TaskId));
                        // trans.Commit();
                    }


                }
                catch
                {
                    //if (sb.Length > 0)
                    //{
                    //    trans.Rollback();
                    //}
                    throw;
                }
                finally
                {
                    //if (trans.Connection != null)
                    //{
                    //    if (trans.Connection.State == ConnectionState.Open)
                    //    {
                    //        trans.Connection.Close();
                    //        trans.Connection.Dispose();
                    //    }
                    //}
                    if (cmd.Connection.State == ConnectionState.Open)
                    {
                        cmd.Connection.Close();
                        cmd.Connection.Dispose();
                        cmd.Dispose();
                    }
                    if (trans != null)
                    {
                        trans.Dispose();
                    }
                }

            }
            catch (Exception ex) //意外终止
            {
                LogUtil.Error(ex);
                Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('保存失败!错误信息：" + ex.Message.Replace("'", "").Replace("\r", "").Replace("\n", "") + "');", true);
            }

            Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "saveSuccess();", true);
        }
    }
}